/**
 * @file 地址栏记录服务
 * @description 基于 better-sqlite3 浏览历史记录的地址栏输入提示服务
 *
 * @author ICI SRD
 * @version 3.0.0
 * @since 2025-08-06
 */

import { LOCAL_URL_LIST } from '~shared/constants'

/**
 * 建议项类型定义
 */
export interface SuggestionItem {
  /** 唯一标识符，用于Vue的key */
  id: string
  type: 'history' | 'search' | 'local'
  url: string
  title: string
  favicon?: string
  visitCount: number
  /** 本地URL的描述信息 */
  description?: string
  /** 本地URL的图标名称 */
  icon?: string
}

/**
 * URL规范化函数
 * @param url 原始URL
 * @returns 规范化后的URL
 */
function normalizeUrl(url: string): string {
  try {
    // 如果没有协议，添加 https://
    let normalizedUrl = url
    if (!/^https?:\/\//i.test(url)) {
      normalizedUrl = `https://${url}`
    }

    const urlObj = new URL(normalizedUrl)

    // 移除末尾的斜杠（除非是根路径）
    if (urlObj.pathname !== '/' && urlObj.pathname.endsWith('/')) {
      urlObj.pathname = urlObj.pathname.slice(0, -1)
    }

    // 移除默认端口
    if (
      (urlObj.protocol === 'https:' && urlObj.port === '443') ||
      (urlObj.protocol === 'http:' && urlObj.port === '80')
    ) {
      urlObj.port = ''
    }

    // 移除fragment（#后面的部分）
    urlObj.hash = ''

    return urlObj.toString()
  } catch {
    // 如果URL无效，返回原始URL
    return url.trim()
  }
}

/**
 * 地址栏记录服务类
 * @description 基于 better-sqlite3 浏览历史记录的地址栏输入提示服务
 */
export class AddressBarService {
  /**
   * 获取搜索建议（包含历史记录和搜索引擎建议）
   * @param query 搜索关键词
   * @param limit 返回结果数量限制
   * @param currentUrl 当前地址栏的URL，用于过滤相同的建议
   */
  static async getSearchSuggestions(
    query: string,
    limit = 8,
    currentUrl?: string
  ): Promise<SuggestionItem[]> {
    try {
      const suggestions: SuggestionItem[] = []
      const normalizedCurrentUrl = currentUrl ? normalizeUrl(currentUrl) : ''

      if (!query.trim()) {
        // 空查询时返回最近访问的记录
        const recentResult = await _pre_.browsingHistory.getRecentRecords(limit)
        if (recentResult.success && recentResult.data) {
          const recentSuggestions = recentResult.data
            .map((record, index) => ({
              id: `recent-${record.id || index}`,
              type: 'history' as const,
              url: record.url,
              title: record.title || record.url,
              favicon: record.favicon_url,
              visitCount: record.visit_count
            }))
            // 过滤掉与当前URL相同的建议
            .filter(suggestion => {
              if (!normalizedCurrentUrl) return true
              return normalizeUrl(suggestion.url) !== normalizedCurrentUrl
            })

          return recentSuggestions
        }
        return []
      }

      // 检查是否为本地URL查询
      if (this.isLocalUrlQuery(query)) {
        const localSuggestions = this.generateLocalUrlSuggestions(query, limit)
        suggestions.push(...localSuggestions)
      }

      // 规范化查询词，用于比较
      const normalizedQuery = normalizeUrl(query)

      // 获取历史记录建议
      const remainingHistorySlots = limit - suggestions.length
      if (remainingHistorySlots > 0) {
        const searchResult = await _pre_.browsingHistory.searchRecords(
          query,
          Math.floor(remainingHistorySlots * 0.7)
        )
        if (searchResult.success && searchResult.data) {
          const historySuggestions: SuggestionItem[] = searchResult.data
            .map(record => ({
              id: `history-${record.id}`,
              type: 'history' as const,
              url: record.url,
              title: record.title || record.url,
              favicon: record.favicon_url,
              visitCount: record.visit_count
            }))
            // 过滤掉与当前输入完全匹配的URL
            .filter(suggestion => {
              const normalizedSuggestionUrl = normalizeUrl(suggestion.url)
              // 过滤掉与查询词完全匹配的URL
              if (normalizedSuggestionUrl === normalizedQuery) return false
              // 过滤掉与当前地址栏URL相同的建议
              if (normalizedCurrentUrl && normalizedSuggestionUrl === normalizedCurrentUrl)
                return false
              return true
            })

          suggestions.push(...historySuggestions)
        }
      }

      // 如果历史记录不足，添加搜索建议
      const remainingSlots = limit - suggestions.length
      if (remainingSlots > 0 && this.isSearchQuery(query) && query.indexOf('f2:') > 0) {
        const searchSuggestions = this.generateSearchSuggestions(query, remainingSlots)
        suggestions.push(...searchSuggestions)
      }

      return suggestions.slice(0, limit)
    } catch (error) {
      console.error('❌ 获取搜索建议失败:', error)
      return []
    }
  }

  /**
   * 判断是否为搜索查询（而非URL）
   * @param query 查询词
   * @private
   */
  private static isSearchQuery(query: string): boolean {
    // 简单的URL检测
    const urlPattern = /^(https?:\/\/|www\.|[a-zA-Z0-9-]+\.[a-zA-Z]{2,})/
    return !urlPattern.test(query.trim())
  }

  /**
   * 判断是否为本地URL查询
   * @param query 查询词
   * @private
   */
  private static isLocalUrlQuery(query: string): boolean {
    const trimmedQuery = query.trim().toLowerCase()
    return trimmedQuery.startsWith('f2') || trimmedQuery.startsWith('f2://')
  }

  /**
   * 生成本地URL建议
   * @param query 查询词
   * @param limit 数量限制
   * @private
   */
  private static generateLocalUrlSuggestions(query: string, limit: number): SuggestionItem[] {
    const trimmedQuery = query.trim().toLowerCase()

    // 过滤匹配的本地URL
    const matchedUrls = LOCAL_URL_LIST.filter(localUrl => {
      const url = localUrl.url.toLowerCase()
      const title = localUrl.title.toLowerCase()

      // 如果输入与URL完全匹配，则不显示该建议
      if (trimmedQuery === url) {
        return false
      }

      // 匹配URL或标题
      return (
        url.includes(trimmedQuery) ||
        title.includes(trimmedQuery) ||
        // 特殊处理：如果输入"f2"或"f2://"，显示所有本地URL
        trimmedQuery === 'f2' ||
        trimmedQuery === 'f2://'
      )
    })

    return matchedUrls.slice(0, limit).map((localUrl, index) => ({
      id: `local-${localUrl.url.replace('f2://', '')}-${index}`,
      type: 'local' as const,
      url: localUrl.url,
      title: localUrl.title,
      icon: localUrl.icon,
      favicon: undefined,
      visitCount: 0
    }))
  }

  /**
   * 生成搜索引擎建议
   * @param query 查询词
   * @param limit 数量限制
   * @private
   */
  private static generateSearchSuggestions(query: string, limit: number): SuggestionItem[] {
    const searchEngines = [
      { name: 'Google', url: `https://www.google.com/search?q=${encodeURIComponent(query)}` },
      { name: 'Bing', url: `https://www.bing.com/search?q=${encodeURIComponent(query)}` },
      { name: 'DuckDuckGo', url: `https://duckduckgo.com/?q=${encodeURIComponent(query)}` }
    ]

    return searchEngines.slice(0, limit).map((engine, index) => ({
      id: `search-${engine.name.toLowerCase()}-${index}`,
      type: 'search' as const,
      url: engine.url,
      title: `在 ${engine.name} 中搜索 "${query}"`,
      favicon: undefined,
      visitCount: 0
    }))
  }
}
